﻿using System;
using System.Text;
using System.Windows;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using NorthernLights.Controls;
using NorthernLights.Core;

namespace NorthernLights.Examples
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            /* example of StateVariables */
            NorthernLights.StateVariables.Set<string>("MyPersonalVariable", "MyValue");
            string value = NorthernLights.StateVariables.Get<string>("MyPersonalVariable");

            /* example of PersitentVariables */
            NorthernLights.PersistentVariables.Set<string>("MyPersonalVariable2", "MyValue");
            string value2 = NorthernLights.PersistentVariables.Get<string>("MyPersonalVariable2");

            /* Example of Version Checking */
            NorthernLights.VersionManagement.CheckForNewVersion("http://www.yourwebsite.com/appversion.txt", () =>
            {
                // new version available. open the marketplace.
            });

            /* Example of Version Checking, version 2 */
            NorthernLights.VersionManagement.CheckForNewVersion("http://www.yourwebsite.com/appversion.txt", (result) =>
            {
                if (result)
                {
                    // new version available. open the marketplace.
                }
                else
                {
                    // you are using the latest version. notify the user how cool he is.
                }

            });

            /* Example on how to get your application Version */
            Version version = NorthernLights.VersionManagement.GetVersion();

            if (version != null)
            {
                this.versionTxtBlock.Text = string.Format("Version: {0}", version.ToString());
            }

            /* Exception reporter */
            ExceptionContainer exception = LittleWatson.GetPreviousException();

            if (exception != null)
            {
                if (LittleWatson.Instance.AllowAnonymousHttpReporting)
                {
                    // add as much additional information as you want.
                    string additionalInformation = string.Format("Device manufacturer: {0}{1}OS Version: {2}{1}", DeviceStatus.DeviceManufacturer, Environment.NewLine, Environment.OSVersion.Version);

                    LittleWatson.Instance.SendExceptionToHttpEndpoint("http://www.yourdomain.com/data/post.php", exception, additionalInformation);

                    // original call without any additional information.
                    ////LittleWatson.Instance.SendExceptionToHttpEndpoint("http://www.yourdomain.com/data/post.php", exception);
                }
                else
                {
                    // show popup.
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        EmailComposeTask email = new EmailComposeTask();
                        email.To = "info@youremailaddress.com";
                        email.Subject = "My App: auto-generated problem report";
                        email.Body = exception.Message + Environment.NewLine + exception.StackTrace;
                        email.Show();
                    });
                }
            }

            /* protect data */
            Encryption.ProtectedData.Protect<string>("my incredibily complex long passphrase.", "myappdata", "my secret");
            string mysecret = Encryption.ProtectedData.Unprotect<string>("my incredibily complex long passphrase.", "myappdata");

            /* symmetric encryption */
            byte[] dataToEncrypt = Encoding.UTF8.GetBytes("my secret");
            byte[] password = ByteGenerator.Generate(400);
            byte[] salt = ByteGenerator.Generate(400);

            byte[] encryptedData = Encryption.Symmetric.Encryption.Encrypt(dataToEncrypt, password, salt);
            byte[] mydata = Encryption.Symmetric.Encryption.Decrypt(encryptedData, password, salt);

            mysecret = Encoding.UTF8.GetString(mydata, 0, mydata.Length);

            /* asymmetric encryption */
            Encryption.Asymmetric.Encryption.GenerateKeyAsync(512, (generatedKeypair) =>
            {
                string keypair = generatedKeypair;

                byte[] encryptedMessage = NorthernLights.Encryption.Asymmetric.Encryption.Encrypt(keypair, dataToEncrypt);
                byte[] decryptedMessage = NorthernLights.Encryption.Asymmetric.Encryption.Decrypt(keypair, encryptedMessage);

                mysecret = Encoding.UTF8.GetString(decryptedMessage, 0, decryptedMessage.Length);
            });

            ////NagForReview.Check(Controls.NagForReview.NagType.AfterXDays | Controls.NagForReview.NagType.AfterXTimes, -1, 2);
            NagForReview.Check("Review", "Please review my app", "later", "-review", "-notnow", Controls.NagForReview.NagType.AfterXDays | Controls.NagForReview.NagType.AfterXTimes, -1, 2);
        }

        private void ApplicationBarIconButtonClick(object sender, EventArgs e)
        {
            ApplicationBarIconButton item = sender as ApplicationBarIconButton;

            if (item != null)
            {
                if (string.Compare(item.Text, "settings", StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    // load settings page.
                    this.NavigationService.Navigate(new Uri("/Pages/SettingsPage.xaml", UriKind.Relative));
                }
            }
        }

        private void CrashBtnClick(object sender, RoutedEventArgs e)
        {
            throw new Exception("Manually thrown exception.");
        }

        private void ShowNotBtnClick(object sender, RoutedEventArgs e)
        {
            this.notification.Show(
                "This is a test",
                new SolidColorBrush(Colors.Green),
                () =>
                {
                    /* action to execute on tap */
                });
        }

        private void inputBtnClick(object sender, RoutedEventArgs e)
        {
            InputPopup popup = new InputPopup();
            popup.Completed += (s2, e2) =>
            {
                var input = popup.Input;
            };

            popup.Show("Name", "what is your name?", "ok", "cancel");
        }
    }
}